<template>
  <el-dialog
    :title="isEdit ? '编辑楼层' : '新增楼层'"
    v-model="dialogVisible"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      @submit.prevent
    >
      <el-form-item label="场馆" prop="venueId">
        <el-select
          v-model="formData.venueId"
          placeholder="请选择场馆"
          filterable
          style="width: 100%"
          :disabled="isEdit"
        >
          <el-option
            v-for="venue in venueOptions"
            :key="venue.id"
            :label="`${venue.name} (${venue.city}, ${venue.country})`"
            :value="venue.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="楼层名称" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入楼层名称"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="楼层号" prop="level">
        <el-input-number
          v-model="formData.level"
          :min="-10"
          :max="999"
          placeholder="请输入楼层号"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入楼层描述"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio value="ACTIVE">启用</el-radio>
          <el-radio value="INACTIVE">禁用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="平面图" prop="floorPlan">
        <div class="floor-plan-upload">
          <!-- 当前平面图预览 -->
          <div v-if="currentFloorPlanUrl" class="current-floor-plan">
            <el-image
              :src="currentFloorPlanUrl"
              fit="cover"
              style="width: 200px; height: 120px; border-radius: 8px; border: 1px solid #dcdfe6;"
              preview-teleported
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                  <span>图片加载失败</span>
                </div>
              </template>
            </el-image>
            <div class="floor-plan-info">
              <p class="floor-plan-name">当前平面图</p>
              <el-button
                type="danger"
                size="small"
                @click="handleRemoveFloorPlan"
              >
                删除平面图
              </el-button>
            </div>
          </div>

          <!-- 新上传的平面图预览 -->
          <div v-if="newFloorPlanPreview" class="new-floor-plan">
            <el-image
              :src="newFloorPlanPreview"
              fit="cover"
              style="width: 200px; height: 120px; border-radius: 8px; border: 1px solid #409eff;"
            />
            <div class="floor-plan-info">
              <p class="floor-plan-name">新上传的平面图</p>
              <el-button
                type="danger"
                size="small"
                @click="handleRemoveNewFloorPlan"
              >
                移除
              </el-button>
            </div>
          </div>

          <!-- 文件上传 -->
          <div v-if="!currentFloorPlanUrl && !newFloorPlanPreview" class="upload-area">
            <el-upload
              ref="uploadRef"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleFileChange"
              accept="image/*"
              drag
            >
              <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  只能上传jpg/png文件，且不超过10MB
                </div>
              </template>
            </el-upload>
          </div>

          <!-- 重新上传按钮 -->
          <div v-if="currentFloorPlanUrl || newFloorPlanPreview" class="re-upload">
            <el-upload
              ref="reUploadRef"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleFileChange"
              accept="image/*"
            >
              <el-button type="primary" size="small">
                <el-icon><UploadFilled /></el-icon>
                重新上传
              </el-button>
            </el-upload>
          </div>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules, UploadFile } from 'element-plus'
import { Picture, UploadFilled } from '@element-plus/icons-vue'
import { floorApi, type Floor, type FloorFormData, type VenueOption } from '@/api/floor'

interface Props {
  visible: boolean
  floorData?: Floor | null
  venueOptions: VenueOption[]
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const uploadRef = ref()
const reUploadRef = ref()
const loading = ref(false)
const isEdit = ref(false)

// 平面图相关状态
const currentFloorPlanUrl = ref<string>('')
const newFloorPlanFile = ref<File | null>(null)
const newFloorPlanPreview = ref<string>('')

// 计算属性：对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value: boolean) => emit('update:visible', value)
})

// 表单数据
const formData = reactive<FloorFormData>({
  venueId: 0,
  name: '',
  level: undefined,
  description: '',
  status: 'ACTIVE'
})

// 表单验证规则
const rules: FormRules = {
  venueId: [
    { required: true, message: '请选择场馆', trigger: 'change' },
    { type: 'number', min: 1, message: '请选择有效的场馆', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入楼层名称', trigger: 'blur' },
    { min: 1, max: 50, message: '楼层名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  level: [
    { type: 'number', min: -10, max: 999, message: '楼层号必须在 -10 到 999 之间', trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '描述长度不能超过 500 个字符', trigger: 'blur' }
  ]
}

// 监听对话框显示状态
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      if (props.floorData) {
        // 编辑模式
        isEdit.value = true
        Object.assign(formData, {
          venueId: props.floorData.venueId,
          name: props.floorData.name,
          level: props.floorData.level,
          description: props.floorData.description || '',
          status: props.floorData.status
        })
        currentFloorPlanUrl.value = props.floorData.floorPlanUrl || ''
        newFloorPlanFile.value = null
        newFloorPlanPreview.value = ''
      } else {
        // 新增模式
        isEdit.value = false
        resetForm()
      }
    }
  }
)

// 重置表单
const resetForm = () => {
  formData.venueId = 0
  formData.name = ''
  formData.level = undefined
  formData.description = ''
  formData.status = 'ACTIVE'
  currentFloorPlanUrl.value = ''
  newFloorPlanFile.value = null
  newFloorPlanPreview.value = ''
  formRef.value?.clearValidate()
}

// 关闭对话框
const handleClose = () => {
  emit('update:visible', false)
  resetForm()
}

// 文件选择处理
const handleFileChange = (file: UploadFile) => {
  if (!file.raw) return
  
  // 验证文件类型
  if (!file.raw.type.startsWith('image/')) {
    ElMessage.error('只能上传图片文件')
    return
  }
  
  // 验证文件大小 (10MB)
  if (file.raw.size > 10 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过10MB')
    return
  }
  
  newFloorPlanFile.value = file.raw
  // 使用 FileReader 替代 URL.createObjectURL 来避免 CSP 问题
  const reader = new FileReader()
  reader.onload = (e) => {
    if (e.target?.result) {
      newFloorPlanPreview.value = e.target.result as string
    }
  }
  reader.readAsDataURL(file.raw)
  // newFloorPlanPreview.value = URL.createObjectURL(file.raw)
}

// 删除当前平面图
const handleRemoveFloorPlan = () => {
  currentFloorPlanUrl.value = ''
  newFloorPlanFile.value = null
  newFloorPlanPreview.value = ''
}

// 移除新上传的平面图
const handleRemoveNewFloorPlan = () => {
  newFloorPlanFile.value = null
  if (newFloorPlanPreview.value) {
    URL.revokeObjectURL(newFloorPlanPreview.value)
    newFloorPlanPreview.value = ''
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    // 创建FormData
    const formDataToSend = new FormData()
    formDataToSend.append('venueId', formData.venueId.toString())
    formDataToSend.append('name', formData.name)
    if (formData.level !== undefined) {
      formDataToSend.append('level', formData.level.toString())
    }
    if (formData.description) {
      formDataToSend.append('description', formData.description)
    }
    formDataToSend.append('status', formData.status)
    
    // 如果有新上传的平面图文件
    if (newFloorPlanFile.value) {
      formDataToSend.append('floorPlan', newFloorPlanFile.value)
    }

    if (isEdit.value && props.floorData) {
      // 更新楼层
      await floorApi.update(props.floorData.id, formDataToSend)
      ElMessage.success('楼层更新成功')
    } else {
      // 创建楼层
      await floorApi.create(formDataToSend)
      ElMessage.success('楼层创建成功')
    }

    emit('success')
    handleClose()
  } catch (error: any) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('操作失败，请重试')
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

.floor-plan-upload {
  .current-floor-plan,
  .new-floor-plan {
    display: flex;
    align-items: flex-start;
    gap: 15px;
    margin-bottom: 15px;
    padding: 15px;
    border: 1px solid #dcdfe6;
    border-radius: 8px;
    background-color: #fafafa;
  }

  .new-floor-plan {
    border-color: #409eff;
    background-color: #f0f9ff;
  }

  .floor-plan-info {
    flex: 1;
    
    .floor-plan-name {
      margin: 0 0 10px 0;
      font-weight: 500;
      color: #606266;
    }
  }

  .upload-area {
    border: 2px dashed #d9d9d9;
    border-radius: 8px;
    padding: 20px;
    text-align: center;
    background-color: #fafafa;
    transition: border-color 0.3s;

    &:hover {
      border-color: #409eff;
    }

    .el-icon--upload {
      font-size: 28px;
      color: #8c939d;
      margin-bottom: 10px;
    }

    .el-upload__text {
      color: #606266;
      font-size: 14px;
      
      em {
        color: #409eff;
        font-style: normal;
      }
    }

    .el-upload__tip {
      font-size: 12px;
      color: #909399;
      margin-top: 10px;
    }
  }

  .re-upload {
    margin-top: 15px;
    text-align: center;
  }

  .image-error {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 200px;
    height: 120px;
    background-color: #f5f7fa;
    border-radius: 8px;
    border: 1px dashed #dcdfe6;
    color: #909399;
    
    .el-icon {
      font-size: 24px;
      margin-bottom: 8px;
    }
    
    span {
      font-size: 12px;
    }
  }
}
</style>
